﻿using System;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using TianShu.LicenseAuthorizer.Abstracts.Service;
using Volo.Abp;
using Volo.Abp.Clients;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Localization;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Timing;

namespace TianShu.LicenseAuthorizer.Abstracts.Middleware
{
    public class LicenseAuthMiddleware : IMiddleware, ITransientDependency
    {
        private readonly ICurrentTenant _currentTenant;
        private readonly ICurrentClient _currentClient;
        private readonly ILiceseLoaderService _liceseLoaderService;
        private readonly IClock _clock;

        public LicenseAuthMiddleware(
            ICurrentTenant currentTenant
            , ICurrentClient currentClient
            , ILiceseLoaderService liceseLoaderService
            , IClock clock)
        {
            liceseLoaderService.CheckLicenseLoaderServiceImpl();

            _currentTenant = currentTenant;
            _currentClient = currentClient;
            _liceseLoaderService = liceseLoaderService;
            _clock = clock;
        }

        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (_currentTenant.Id.HasValue)
            {
                if (_currentClient.IsAuthenticated==false)
                {
                    throw new UserFriendlyException("客户端未授权");
                }
                var licenseAuthInfo = _liceseLoaderService.CheckLicenseAuthorizer(_currentTenant.Id.Value, _currentClient.Id?.ToString());
            }

            await next(context);
        }

    }
}
